package pr.lanmu.config.util;

import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实体类转换工具，转单个或List
 */
public class ConvertUtil {
    public static <T, E> E copy(T source, E e) {
        if (source == null) return e;
        BeanUtils.copyProperties(source, e);
        return e;
    }

    @SneakyThrows
    public static <T, E> List<E> listToType(List<T> list, Class<E> clazz) {
        Constructor<E> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        return list.parallelStream()
                .map(t -> {
                    E e = null;
                    try {
                        e = declaredConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
                        ex.printStackTrace();
                    }
                    return ConvertUtil.copy(t, e);
                })
                .collect(Collectors.toList());
    }
}